package com.common.web.util;

import java.io.BufferedReader;
import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.util.IOUtils;
import com.common.web.service.JwtTokenUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author ficus
 * 解析requset工具类
 */
@Slf4j
@Component
@Lazy(false)
public class RequestUtil {

	@Autowired
	private JwtTokenUtil jwtTokenUtil;
    
    private static JwtTokenUtil sjwtTokenUtil;
	
	@PostConstruct
    public void init() {
		sjwtTokenUtil=jwtTokenUtil;
    }
    
	/**
	 * 获取请求URL
	 * @param request
	 * @return
	 */
	public static String getRequestUrl(HttpServletRequest request) {
		return request.getRequestURI();
	}
	
    /**
     * 获取请求来源IP
     * @return
     */
    public static String getRequestIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
	
    public static HttpServletRequest getRequest() {
		 ServletRequestAttributes attributes= (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
		 return attributes.getRequest();
	}
    
	/**
	 * 获取post请求参数
	 * @param request
	 * @return
	 */
	public static String getRequestParam(HttpServletRequest request) {
		StringBuffer buffer = new StringBuffer();
		String line = null;
		BufferedReader reader = null;
		try {
			reader = request.getReader();
			while (null != (line = reader.readLine())) {
				buffer.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
			log.warn("获取请求参数异常:"+e.toString());
		} finally {
			IOUtils.close(reader);
		}
		return buffer.toString();
	}
    	
	/**
	 * 从token中获取登录用户编码和名称
	 */
	public static String[] getUserCodeAndName() {
		return sjwtTokenUtil.getUserCodeAndName(getRequest());
	}
	
	/**
	 * 获取当前用户编码
	 * @return
	 */
	public static String getUserCode() {
		return sjwtTokenUtil.getUserCode(getRequest());
	}
	
	/**
	 * 获取当前用户名称
	 * @return
	 */
	public static String getUserName() {
		return sjwtTokenUtil.getUserName(getRequest());
	}
}
